<?php

/**
 * This is the model class for table "{{ticket}}".
 *
 * The followings are the available columns in table '{{ticket}}':
 * @property integer $zti_id
 * @property integer $zm_id
 * @property string $zti_title
 * @property integer $zti_type
 * @property integer $zti_card_type
 * @property string $zti_num_start
 * @property string $zti_num_end
 * @property double $zti_condition
 * @property double $zti_value
 * @property integer $zti_inventory
 * @property integer $zti_limitget
 * @property string $zti_content
 * @property string $zti_pic
 * @property integer $zti_start_time
 * @property integer $zti_end_time
 * @property integer $zti_point
 * @property integer $zti_status
 * @property integer $inputtime
 * @property integer $updatetime
 */
class Ticket extends CActiveRecord
{
	//店铺名称，用于筛选
	public $company_name;
	
	//状态，用于筛选
	public $status;
	
	//优惠券领取条件不满足时的提示信息
	public $limitMessage = array(
				0=>'此优惠券可以领取。',
				1=>'领取数量达到上限。',
				2=>'此优惠券已领完。',
				3=>'此优惠券已过期。',
				4=>'领取数量超过剩余数量。',
				5=>'优惠券不存在或已被删除。',
				6=>'不能领取自己发布的优惠券。',
			);
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Ticket the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{ticket}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zm_id, zti_type, zti_card_type, zti_limitget, zti_point,status', 'numerical', 'integerOnly'=>true),
			array('zti_condition, zti_value,zti_inventory,zti_issuance_number', 'numerical'),
			array('zti_title', 'length', 'max'=>100),
			array('zti_num_start, zti_num_end', 'length', 'max'=>20),
			array('zti_pic, zti_start_time, zti_end_time, company_name', 'length', 'max'=>255),
			array('zti_inventory','length','min'=>1),
			array('zti_content', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zti_id, zm_id, zti_title, zti_type, zti_card_type, company_name, zti_num_start, zti_num_end, zti_condition, zti_value, zti_inventory, zti_limitget, zti_content, zti_pic, zti_start_time, zti_end_time, zti_point, zti_status, inputtime', 'safe', 'on'=>'search'),
		);
		    array('zti_status','in','range'=>array(1,2,3));
			array('zti_value','in','range'=>array(3,5,10,20,50,100));
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'company'=>array(self::BELONGS_TO, 'Company', 'zm_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zti_id' => 'Id',
			'zm_id' => '会员Id',
			'zti_title' => '优惠券名称',
			'zti_type' => '优惠券类型',//优惠券，现金券
			'zti_card_type' => '卡的类型',//实体卡，电子卡
			'zti_num_start' => '实体卡开始编号',
			'zti_num_end' => '实体卡结束编号',
			'zti_condition' => '使用满足金额',
			'zti_value' => '优惠券面额值',//限3、5、10、20、50、100
			'zti_issuance_number' => '发行数量',
			'zti_inventory' => '剩余数量',
			'zti_limitget' => '限领数量',
			'zti_content' => '介绍',
			'zti_pic' => '图片地址',
			'zti_start_time' => '开始时间',
			'zti_end_time' => '结束时间',
			'zti_point' => '兑换积分',
			'zti_status' => '状态',//1开启2关闭
			'inputtime' => '录入时间',
			'updatetime' => '修改时间',
		);
	}
	
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('zti_id',$this->zti_id);
		$criteria->compare('zti_title',$this->zti_title,true);
		$criteria->compare('zti_type',$this->zti_type);
		$criteria->compare('zti_card_type',$this->zti_card_type);
		$criteria->compare('zti_num_start',$this->zti_num_start,true);
		$criteria->compare('zti_num_end',$this->zti_num_end,true);
		$criteria->compare('zti_condition',$this->zti_condition);
		$criteria->compare('zti_value',$this->zti_value);
		$criteria->compare('zti_issuance_number',$this->zti_issuance_number);
		$criteria->compare('zti_inventory',$this->zti_inventory);
		$criteria->compare('zti_limitget',$this->zti_limitget);
		$criteria->compare('zti_content',$this->zti_content,true);
		$criteria->compare('zti_pic',$this->zti_pic,true);

		$criteria->compare('zti_point',$this->zti_point);
		$criteria->compare('zti_status',$this->zti_status);
		$criteria->compare('inputtime',$this->inputtime);
		$criteria->compare('updatetime',$this->updatetime);
		//根据公司名称筛选
		if(!empty($this->company_name)){
			$criteria->join = ' LEFT JOIN {{Company}} c ON c.zm_id=t.zm_id ';
			$criteria->addCondition(' c.zc_name like "%'.$this->company_name.'%" ');
		}else{
			$criteria->compare('zm_id',$this->zm_id);
		}
		
		//根据状态查询
		if(!empty($this->status)){
			if($this->status==1){
				$criteria->compare('zti_start_time','<='.time());
				$criteria->compare('zti_end_time','>='.time());
			}elseif($this->status==2){
				$criteria->compare('zti_start_time','>'.time());
			}elseif($this->status==3){
				$criteria->compare('zti_end_time','<'.time());
			}
		}else{
			$criteria->compare('zti_start_time',$this->zti_start_time);
			$criteria->compare('zti_end_time',$this->zti_end_time);
		}

		$criteria->order = " inputtime DESC ";//默认为时间倒序
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	protected function beforeSave(){
	    if (parent::beforeSave()){	        
	        if($this->isNewRecord){
	            $this->inputtime = $this->updatetime = time();
	            $this->zm_id = Company::model()->getCmpUserId();
	            $this->zti_issuance_number = $this->zti_inventory;
	        }else{
	        	$this->updatetime = time();	
	        }	     
	        return true;
	    }else{
	        return false;
	    }
	}
	
	/**
	 * 统计不同类型优惠券数量：可使用、已使用、已过期
	 */
	public function amountOfStatus($memberid){
		$criteria = new CDbCriteria();
		$criteria->compare('zmi_start_time','<'.time());
		$criteria->compare('zmi_end_time','>'.time());
		$criteria->compare('zmi_status','2');
		//可用数量
		$sql = 'select sum(zmi_num) as amount from {{mem_ticket}} where zm_id='.$memberid.' and zmi_start_time<'.time().' and zmi_end_time>'.time().' and zmi_status=1';
		$amount['available'] = Yii::app()->db->createCommand($sql)->queryRow();
		//已过期数量
		$sql = 'select sum(zmi_num) as amount from {{mem_ticket}} where zm_id='.$memberid.' and zmi_end_time<'.time().' and zmi_status=1';
		$amount['expired'] = Yii::app()->db->createCommand($sql)->queryRow();
		//已使用数量
		$sql = 'select sum(zmi_num) as amount from {{mem_ticket}} where zm_id='.$memberid.' and zmi_status=2';
		$amount['used'] = Yii::app()->db->createCommand($sql)->queryRow();
		foreach($amount as $key=>$value){
			$amount[$key] = $value['amount'] ? $value['amount'] : '0';
		}
		return $amount;
	}
	
	/**
	 * 优惠券中心列表数据
	 * @return CActiveDataProvider 
	 */
	public function centerList()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('zti_type',1);
		$criteria->compare('zti_card_type',2);
		$criteria->compare('zti_end_time','>'.time());
		$criteria->compare('zti_status',1);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * 检查会员领取限制
	 * param $memberid 会员id
	 * param $ticketid 优惠券id
	 * param $number 领取数量
	 * return 0.可领取 1.领取数量达到上限 2.已领完 3.已过期 4.领取数量超过剩余数量 5.优惠券不存在或已被删除 6.不能领取自己发布的优惠券
	 */
	public function checkLimit($memberid,$ticketid,$number=1)
	{
		$ticket     = $this->findByPk($ticketid);
		if($memberid==$ticket->zm_id){
			return 6;
		}elseif(!$ticket){
			return 5;
		}elseif( $ticket->zti_end_time < time() ){
			return 3;
		}elseif( $ticket->zti_inventory<=0 ){
			return 2;
		}
		$memTicket  = MemTicket::model()->findAll('zm_id=:memberid and zti_id=:ticketid',array(':memberid'=>$memberid,':ticketid'=>$ticketid));
		$memAmount = 0;
		if($memTicket){
			foreach($memTicket as $mt){
				$memAmount += $mt->zmi_num;
			}
		}
		if( $ticket->zti_limitget <= $memAmount ){
			return 1;
		}elseif( $ticket->zti_limitget < $memAmount+$number ){
			return 4;
		}
		return 0;
	}
	
	/**
	 * 优惠券面值
	 */
	public function getZtiValue($type=null){
		if($type==null){
			return array(
				'3.00'=>'3元',	
				'5.00'=>'5元',
				'10.00'=>'10元',
				'20.00'=>'20元',
				'30.00'=>'30元',
				'50.00'=>'50元',
				'100.00'=>'100元',
			);
		}
	}
	
	/**
	 * 优惠券皮肤
	 */
	public function getZtiPic($type=null){
		if($type==null){
			return array(
					'coupon01'=>'skin skin_01',
					'coupon02'=>'skin skin_02',
					'coupon03'=>'skin skin_03',
			);
		}
	}

	/**
	 * 状态，用于筛选
	 */
	public function getStatus($type=null){
		if($type==null){
			return array(
					''=>'全部',
					'1'=>'正在进行',
					'2'=>'未开始',
					'3'=>'已结束',
			);
		}
	}
}